import XLSX from 'xlsx'
let fileSaver = require('file-saver')
let html2canvas = require('html2canvas')

const setTitle = (title) => { // 设置页面title
  document.title = title
}

let params = string => { // 获取url参数值
  let reg = new RegExp('(^|&)' + string + '=([^&]*)(&|$)')
  let r = window.location.search.substr(1).match(reg)
  if (r) return decodeURI(r[2])
  return false
}

// 金额处理
let priceSwitch = (x) => {
  // 强制保留两位小数
  var f = parseFloat(x)
  if (isNaN(f)) return false
  f = Math.round(x * 100) / 100
  var s = f.toString()
  var rs = s.indexOf('.')
  if (rs < 0) {
    rs = s.length
    s += '.'
  }
  while (s.length < (rs + 1) + 2) {
    s += '0'
  }
  // 每三位用一个逗号隔开
  var leftNum = s.split('.')[0]
  var rightNum = '.' + s.split('.')[1]
  var result
  // 定义数组记录截取后的价格
  var resultArray = []
  if (leftNum.length > 3) {
    var i = true
    while (i) {
      resultArray.push(leftNum.slice(-3))
      leftNum = leftNum.slice(0, leftNum.length - 3)
      if (leftNum.length < 4) {
        i = false
      }
    }
    // 由于从后向前截取，所以从最后一个开始遍历并存到一个新的数组，顺序调换
    var sortArray = []
    for (var j = resultArray.length - 1; j >= 0; j--) {
      sortArray.push(resultArray[j])
    }
    result = leftNum + ',' + sortArray.join(',') + rightNum
  } else {
    result = s
  }
  return result
}

// 深拷贝
let deepClone = data => {
  let type = data && data.constructor === Array ? [] : {}
  for (let item in data) {
    if (typeof data[item] === 'object') {
      type[item] = deepClone(data[item])
    } else {
      type[item] = data[item]
    }
  }
  return type
}

let canvasImg = async (domvues, Imgname) => {
  // type 默认为 image/png image/jpeg 或 image/webp 可以从 0 到 1 的区间内选择画质
  let width = domvues.offsetWidth
  let height = domvues.offsetHeight
  let canvasdata = await html2canvas(domvues, {
    dpi: window.devicePixelRatio * 2,
    scale: 2,
    width: width,
    heigth: height
  })
  let imgurl = canvasdata.toDataURL()
  if (Imgname) {
    downloadImg(imgurl, Imgname)
  } else {
    return imgurl
  }
}

// 将数组按一定长度分割
let chunk = (array, size) => {
  // 获取数组的长度，如果你传入的不是数组，那么获取到的就是undefined
  const length = array.length
  // 判断不是数组，或者size没有设置，size小于1，就返回空数组
  if (!length || !size || size < 1) {
    return []
  }
  // 核心部分
  let index = 0 // 用来表示切割元素的范围start
  let resIndex = 0 // 用来递增表示输出数组的下标

  // 根据length和size算出输出数组的长度，并且创建它。
  let result = new Array(Math.ceil(length / size))
  // 进行循环
  while (index < length) {
    // 循环过程中设置result[0]和result[1]的值。该值根据array.slice切割得到。
    result[resIndex++] = array.slice(index, (index += size))
  }
  // 输出新数组
  return result
}

// 时间过滤，flag：false 时间戳， true Date对象
let vueTimeFormat = (val, fmt, flag = false) => {
  let data = flag ? val : new Date(val * 1000)
  let o = {
    'M+': data.getMonth() + 1, // 月份
    'd+': data.getDate(), // 日
    'h+': data.getHours(), // 小时
    'm+': data.getMinutes(), // 分
    's+': data.getSeconds(), // 秒
    'q+': Math.floor((data.getMonth() + 3) / 3), // 季度
    'S': data.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (data.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
  }
  return fmt
}

let add = (arg1, arg2) => {
  let r1
  let r2
  let m
  let c
  try {
    r1 = arg1.toString().split('.')[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split('.')[1].length
  } catch (e) {
    r2 = 0
  }
  c = Math.abs(r1 - r2)
  m = Math.pow(10, Math.max(r1, r2))
  if (c > 0) {
    let cm = Math.pow(10, c)
    if (r1 > r2) {
      arg1 = Number(arg1.toString().replace('.', ''))
      arg2 = Number(arg2.toString().replace('.', '')) * cm
    } else {
      arg1 = Number(arg1.toString().replace('.', '')) * cm
      arg2 = Number(arg2.toString().replace('.', ''))
    }
  } else {
    arg1 = Number(arg1.toString().replace('.', ''))
    arg2 = Number(arg2.toString().replace('.', ''))
  }
  return (arg1 + arg2) / m
}

let sub = (arg1, arg2) => {
  let r1
  let r2
  let m
  let n
  try {
    r1 = arg1.toString().split('.')[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split('.')[1].length
  } catch (e) {
    r2 = 0
  }
  m = Math.pow(10, Math.max(r1, r2))
  n = (r1 >= r2) ? r1 : r2
  return Number(((arg1 * m - arg2 * m) / m).toFixed(n))
}

let mul = (arg1, arg2) => {
  let m = 0
  let s1 = arg1.toString()
  let s2 = arg2.toString()
  try {
    m += s1.split('.')[1].length
  } catch (e) {}
  try {
    m += s2.split('.')[1].length
  } catch (e) {}
  return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m)
}

let div = (arg1, arg2) => {
  let t1 = 0
  let t2 = 0
  let r1
  let r2
  try {
    t1 = arg1.toString().split('.')[1].length
  } catch (e) {}
  try {
    t2 = arg2.toString().split('.')[1].length
  } catch (e) {}
  r1 = Number(arg1.toString().replace('.', ''))
  r2 = Number(arg2.toString().replace('.', ''))
  return (r1 / r2) * Math.pow(10, t2 - t1)
}

let timeHandle = (dateTime) => {
  if (dateTime) {
    let startTime = vueTimeFormat(dateTime[0], 'yyyy-MM-dd', true) + ' 00:00:00'
    let endTime = vueTimeFormat(dateTime[1], 'yyyy-MM-dd', true) + ' 23:59:59'
    startTime = parseInt(new Date(startTime).getTime() / 1000)
    endTime = parseInt(new Date(endTime).getTime() / 1000)
    return [startTime, endTime]
  } else {
    return ['', '']
  }
}

let Storage = {
  get: function (key) {
    if (localStorage.getItem(key) === 'undefined') {
      return
    }
    return JSON.parse(localStorage.getItem(key))
  },
  set: function (key, value) {
    window.localStorage.setItem(key, JSON.stringify(value))
  },
  remove: function (key) {
    window.localStorage.removeItem(key)
  }
}

const headerForExcel = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
let exportExcel = (wscols, excelName, firstCol, list, attr, headertitle, footerdata) => {
  let header = headerForExcel.slice(0, firstCol.length)
  let json = []
  let fistColData = {}
  for (let k in header) {
    fistColData[header[k]] = firstCol[k]
  }
  json.push(fistColData)
  for (let k in list) {
    let res = {}
    for (let i in header) {
      res[header[i]] = list[k][attr[i]]
    }
    json.push(res)
  }
  if (headertitle) {
    for (let h = headertitle.length; h >= 0; h--) {
      json.unshift({'A': headertitle[h]})
    }
  }
  if (footerdata) {
    let obj = {}
    for (let f = 0; f < footerdata.length; f++) {
      obj[headerForExcel[f]] = footerdata[f]
    }
    json.push(obj)
  }
  let wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} }
  // generate workbook object from table 使用xlsx插件写表格
  wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(json, { header: header, skipHeader: true, cellStyles: true })
  wb.Sheets['Sheet1']['!cols'] = wscols
  /* get binary string as output */
  let wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' }) // 转转化为二进制文件
  /* force a download */
  fileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), excelName + '.xlsx') // 使用fileSaver插件生成xlsx文件
}

let eliminateDuplicate = (arrobj) => {
  let arr = arrobj.join('\n')
  let a
  while ((a = arr.replace(/(^.+(?:\r\n|\r|\n|$))((?:.*(?:\r\n|\r|\n))*?)^\1(?:\r\n|\r|\n|$)/m, '$1$2')) !== arr) arr = a
  return arr.split('\n').filter(s => s.length).map(s => parseFloat(s))
}

let downloadImg = (url, name) => {
  var $a = document.createElement('a')
  $a.setAttribute('href', url)
  $a.setAttribute('download', name)
  var evObj = document.createEvent('MouseEvents')
  evObj.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
  $a.dispatchEvent(evObj)
}

let getHostName = () => { // 获取二维码域名
  let hostName = window.location.hostname
  switch (hostName) {
    case 'yihua-test.snsshop.net':
      return 'payexp.snsshop.net'
    case 'edu.yhfinedu.com':
      return 'jy.elebuy.me'
    default:
      return hostName
  }
}

let province = [{'id': 110000, 'name': '北京市'}, {'id': 120000, 'name': '天津市'}, {'id': 130000, 'name': '河北省'}, {'id': 140000, 'name': '山西省'}, {'id': 150000, 'name': '内蒙古自治区'}, {'id': 210000, 'name': '辽宁省'}, {'id': 220000, 'name': '吉林省'}, {'id': 230000, 'name': '黑龙江省'}, {'id': 310000, 'name': '上海市'}, {'id': 320000, 'name': '江苏省'}, {'id': 330000, 'name': '浙江省'}, {'id': 340000, 'name': '安徽省'}, {'id': 350000, 'name': '福建省'}, {'id': 360000, 'name': '江西省'}, {'id': 370000, 'name': '山东省'}, {'id': 410000, 'name': '河南省'}, {'id': 420000, 'name': '湖北省'}, {'id': 430000, 'name': '湖南省'}, {'id': 440000, 'name': '广东省'}, {'id': 450000, 'name': '广西壮族自治区'}, {'id': 460000, 'name': '海南省'}, {'id': 500000, 'name': '重庆市'}, {'id': 510000, 'name': '四川省'}, {'id': 520000, 'name': '贵州省'}, {'id': 530000, 'name': '云南省'}, {'id': 540000, 'name': '西藏自治区'}, {'id': 610000, 'name': '陕西省'}, {'id': 620000, 'name': '甘肃省'}, {'id': 630000, 'name': '青海省'}, {'id': 640000, 'name': '宁夏回族自治区'}, {'id': 650000, 'name': '新疆维吾尔自治区'}, {'id': 710000, 'name': '台湾省'}, {'id': 810000, 'name': '香港特别行政区'}, {'id': 820000, 'name': '澳门特别行政区'}]

export default {
  setTitle,
  params,
  vueTimeFormat,
  timeHandle,
  add,
  sub,
  mul,
  div,
  exportExcel,
  Storage,
  deepClone,
  eliminateDuplicate,
  priceSwitch,
  downloadImg,
  canvasImg,
  chunk,
  getHostName,
  province
}
